package stud.mpgame.policyserver;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PolicyProtocolHandler extends IoHandlerAdapter {

    public static final String[] DEFAULT_POLICY = new String[]{"*:" + 8090};
    public static final String POLICY_REQUEST = "<policy-file-request/>";
    private final static Logger LOGGER = LoggerFactory.getLogger(PolicyProtocolHandler.class);
    private String _policy;

    public PolicyProtocolHandler() {
        super();
        _policy = buildPolicy(DEFAULT_POLICY);
    }

    public PolicyProtocolHandler(String[] allowedHosts_) {
        super();
        if (allowedHosts_ == null) allowedHosts_ = DEFAULT_POLICY;
        _policy = buildPolicy(allowedHosts_);
    }

    private String buildPolicy(String[] allowedHosts_) {
        StringBuffer policyBuffer = new StringBuffer();

        policyBuffer.append("<?xml version=\"1.0\"?><cross-domain-policy>");
        for (String allowedHost : allowedHosts_) {
            String[] hostInfo = allowedHost.split(":");
            String hostname = hostInfo[0];
            String ports;
            if (hostInfo.length > 1) ports = hostInfo[1];
            else ports = "*";

            policyBuffer.append("<allow-access-from domain=\"").append(hostname).append("\" to-ports=\"").append(ports).append("\" />");
        }
        policyBuffer.append("</cross-domain-policy>");

        return policyBuffer.toString();
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        super.sessionCreated(session);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        super.sessionIdle(session, status);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        super.exceptionCaught(session, cause);
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        super.messageSent(session, message);
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        String theMessage = (String) message;
        if (theMessage.equals(POLICY_REQUEST)) {
            session.write(_policy);
            session.close(true);
        }
    }

}
